﻿
namespace Patterns4Net.ArchitectureExplorer.ViewModels.Results
{
    using System;
    using System.ComponentModel.Composition;
    using System.Threading;
    using Caliburn.Micro;
    using Diagram;
    using Services;

    /// <summary>
    /// Represents a result that invokes the Pattern Enforcer in separate thread.
    /// </summary>
    public class RunPatternEnforcer : IResult
    {
        private readonly Diagram diagram;

        /// <summary>
        /// Initializes a new instance of the <see cref="RunPatternEnforcer"/> class.
        /// </summary>
        /// <param name="diagram">The diagram on which the enforcement should be performed.</param>
        public RunPatternEnforcer(Diagram diagram)
        {
            this.diagram = diagram;
        }

        /// <summary>
        /// Gets or sets the pattern enforcer execution service.
        /// </summary>
        [Import]
        public PatternEnforcerWrapper PatternEnforcerWrapper { get; set; }

        /// <summary>
        /// Executes the Pattern Enforcer on given diagram.
        /// </summary>
        /// <param name="context">The execution context. Required by base method signature, but not used.</param>
        public void Execute(ActionExecutionContext context)
        {
            new Thread(() =>
                {
                    this.PatternEnforcerWrapper.RunPatternEnforcer(this.diagram);
                    if (this.Completed != null)
                    {
                        this.Completed(this, new ResultCompletionEventArgs { WasCancelled = false });
                    }
                }).Start();
        }

        /// <summary>
        /// Occurs when execution has completed.
        /// </summary>
        public event EventHandler<ResultCompletionEventArgs> Completed;
    }
}
